package com.bbseguros.pesquisador.action;

import java.io.File;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.struts2.util.ServletContextAware;

import com.bbseguros.pesquisador.bean.UserBean;
import com.bbseguros.pesquisador.dao.UserDAO;
import com.bbseguros.pesquisador.util.ImageCreator;
import com.bbseguros.pesquisador.util.Util;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginSenhaAction extends ActionSupport implements ServletContextAware {

	private static final long serialVersionUID = 1L;
	private static final String DIR_TEMP_IMAGES = File.separator+"images"+File.separator+"tmp"+File.separator;
	private UserBean user;
	private String message;
	private String caracteres;
	private String requestType;
	private String fileName;

	private ServletContext servletContext;

	private static Logger logger = Logger.getLogger(LoginSenhaAction.class);

	public String execute() throws Exception {
		// get exact path for download
		ServletContext context = getServletContext();
		String realPath = context.getRealPath("/");
		int randomNumber = Util.generateRandomNumber();
		
		logger.debug("RandomNumber: "+randomNumber);
		
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put("number",String.valueOf(randomNumber));

		String destDir = realPath + DIR_TEMP_IMAGES;

		File dirPath = new File(destDir); 
		if (!dirPath.exists()) 
		{ 
			logger.debug("Diretorio '"+destDir+"' nao existe. Criando==>> " + dirPath); 
			dirPath.mkdirs(); 
		} 
		
		setFileName(".."+DIR_TEMP_IMAGES+Util.transformFileName(randomNumber)+".png");
		
		String sourceFile = realPath + "images" + File.separator + "scratch.gif";
		
		String destFile = realPath + getFileName().substring(2);
		
		logger.debug("sourceFile: "+sourceFile);
		logger.debug("destFile: "+destFile);
		
		ImageCreator ic = new ImageCreator(sourceFile, destFile, String.valueOf(randomNumber));
		ic.generateImage();
		
		logger.debug(realPath);
	
		return SUCCESS;
	}

	public void validate() {
		boolean hasError = false;

		if (getUser() != null) {
			if (getUser().getCodigo_usuario() != null) {
				if (getUser().getCodigo_usuario().length() == 0) {
					hasError = true;
					addFieldError("user.codigo_usuario", getText("user.required"));
				}
			}
		}

		if (getCaracteres() != null) {
			if (getCaracteres().length() == 0) {
				hasError = true;
				addFieldError("caracteres", getText("caracteres.required"));
			} else {
				Map<String, Object> session = ActionContext.getContext().getSession();
				String idImage = (String)session.get("number");

				logger.debug("IDIMAGE: '"+idImage+"' '"+getCaracteres()+"'");
				
				if (!idImage.equals(getCaracteres())) {
					hasError = true;
					addFieldError("caracteres", getText("caracteres.wrong"));
				}
			}
		}

		if (hasError) {
			setRequestType("fail");
		}
	}

	public String sendMail() {
		String retorno = "recovered";

		user = UserDAO.getInstance().selectUserByUserCode(user.getCodigo_usuario());

		if (user == null) {
			logger.debug(getText("forgot.fail"));
			addActionError(getText("forgot.fail"));
			retorno = ERROR;
		} else {
			logger.debug("Email: " + user.getEmail());
			Util.sendMail(user);
			setMessage(getText("forgot.success"));
			setRequestType("success");
		}

		return retorno;
	}

	public UserBean getUser() {
		return user;
	}

	public void setUser(UserBean user) {
		this.user = user;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getCaracteres() {
		return caracteres;
	}

	public void setCaracteres(String caracteres) {
		this.caracteres = caracteres;
	}

	public String getRequestType() {
		return requestType;
	}

	public void setRequestType(String requestType) {
		this.requestType = requestType;
	}

	private ServletContext getServletContext() {
		return servletContext;
	}

	public void setServletContext(ServletContext arg0) {
		this.servletContext = arg0;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
}
